﻿/**
 * 2014年2月9日4:39:16 .NET4的sqlite的共享调用
 */

using System;
using System.Data;
using System.Data.SQLite;

namespace Mrsoft.SSC.DAL
{
    public static class SqliteHelper
    {
        private const string dataSource = @".\data.db";

        public static int ExecuteNonQuery(string sql) {
            var conSb = new SQLiteConnectionStringBuilder { DataSource = dataSource };
            using (var conn = new SQLiteConnection(conSb.ToString())) {
                conn.Open();
                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = sql;
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// 将时间类型转换为sqlite支持的文本格式
        /// </summary>
        /// <returns></returns>
        public static string ToSqliteTimeString(this DateTime theOne) {
            return theOne.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static DataTable ExecuteTable(string sql) {
            var conSb = new SQLiteConnectionStringBuilder { DataSource = dataSource };
            using (var conn = new SQLiteConnection(conSb.ToString())) {
                conn.Open();
                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = sql;
                    var table = new DataTable();
                    using (SQLiteDataAdapter adp = new SQLiteDataAdapter(cmd)) {
                        adp.Fill(table);
                    }
                    return table;
                }
            }
        }

    }
}
